<?php

class BaseOneTableModule extends BaseModule{
	public function __construct($p){
		if(!$this->table)throw new Exception('Table property must be defined before parent constructor call');
	}
	
	public function listAction($p){
		global $app;
		$flds=$this->table->getFields();
		if(!isset($p['fields']))$p['fields']=array_keys($flds);
		$q=$this->table->buildQuery($p['fields']);
		

		//$this->table->getDB()->print_html($rs);
		if(!isset($p['sortby'])){
			$p['sortby']=$this->table->getPrimaryKey();
			$p['sortasc']=0;
		}
		
		$view=new CListExView($this);
		$p[ACTION]='edit';
		$view->table=&$this->table;
		$view->render($q,$p);
		$app->addContextMenuItem(link_for('new/edit'),translate('Create new'));
	}
	
	public function showAction($p){
		if(!isset($p[P0]))throw new Exception('Not enough parameter: P0');
		$e=$this->table->getByPK($p[P0]);
		if(!$e)throw new Exception('Record does not exist: #'.$p[P0]);
		$e->dump();
		echo html_tag(Array(
			'tagName'=>'a',
			'href'=>link_for($e->pk.'/edit'),
			'innerHTML'=>translate('edit'),
		));
	}
	
	public function editAction($p){
		global $app;
		if(!isset($p[P0]))throw new Exception('Not enough parameter: P0');
		$e=$this->table->getByPK($p[P0]);
		if(!$e)throw new Exception('Record does not exist: #'.$p[P0]);
		$clsn=(string)$this->table.'Form';
		
		try{
			$form=new $clsn;
		}catch(Exception $e){
			BaseForm::generate((string)$this->table);
			$form=new $clsn;
		};
		
		$app->addContextMenuItem(link_for('list'),'Go back to list');
		$form->loadfromrecord($e);
		$form->renderwithtemplate();
	}
	
	public function doeditAction($p){
		if(!isset($p[P0]))throw new Exception('Not enough parameter: P0');
		$e=$this->table->getByPK($p[P0]);
		if(!$e)throw new Exception('Record does not exist: #'.$p[P0]);
		$clsn=(string)$this->table.'Form';
		$form=new $clsn;
		$form->process($_POST);
		$form->save($e);
		$this->redirectTo(link_for($e->id.'/edit'));
	}
	
	public function deleteAction($p){		
		if(!isset($p[P0]))throw new Exception('Not enough parameter: P0');
		$e=$this->table->getByPK($p[P0]);
		if(!$e)throw new Exception('Record does not exist: #'.$p[P0]);
		$e->delete();
		$this->redirectTo(link_for('list'));
	}
	
}
